package track2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;

public class TrackReflectDemo {
    public static void main(String[] args) throws Exception {
        /**
         * 反射可以和配置文件相结合，动态的创建对象，并调用方法
         */

        //1.读取配置文件中的信息
        Properties properties = new Properties();
        FileInputStream inputStream=new FileInputStream("D:\\code\\interview-java\\prop.properties");
        properties.load(inputStream);
        inputStream.close();
        System.out.println(properties);


        //获取全类名和方法名
        String classname = (String) properties.get("classname");
        String methodName = (String) properties.get("method");

        //利用反射创建对象并运行方法
        Class<?> aClass = Class.forName(classname);

        //获取构造方法
        Constructor<?> con = aClass.getDeclaredConstructor();
        Object o = con.newInstance();//获取对象
        System.out.println(o);

        //获得成员方法并运行
        Method declaredMethod = aClass.getDeclaredMethod(methodName);
        declaredMethod.setAccessible(true);
        declaredMethod.invoke(o);
    }
}
